package moe.server;

import java.io.IOException;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.protocol.HttpContext;

public class ImageCacheInterceptor implements HttpRequestInterceptor {

	public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
		HttpSession session = getSession(context);
		if (session == null) {
			return;
		}
		ImageCache cache = getCache(session);
		if (cache == null) {
			createCache(session);
		}
	}

	private HttpSession getSession(HttpContext context) {
		HttpSession session = null;
		Object o = context.getAttribute(HttpSession.SESSION_CONTEXT);
		if (o != null) {
			session = (HttpSession) o;
		}
		return session;
	}

	private ImageCache getCache(HttpSession session) {
		ImageCache cache = null;
		Object o = session.getAttribute(ImageCache.CACHE_CONTEXT);
		if (o != null) {
			cache = (ImageCache) o;
		}
		return cache;
	}

	private void createCache(HttpSession session) {
		session.setAttribute(ImageCache.CACHE_CONTEXT, new ImageCache());
	}
}
